'use strict'

module.exports = app => {
  class TopicService extends app.Service {
    constructor(ctx) {
      super(ctx);
      this.root = 'https://cnodejs.org/api/v1';
    }

    async list(query) {
      const { article_id, limit, page } = query
      const sql = `SELECT comment.id, comment.content,  comment.reply_count, comment.floor_num, comment.create_at, reply.content as reply_content, 
      comment.from_uid,                 comment_user.name as comment_user_name, comment_user.realname as comment_user_realname,
      reply.id as reply_id,
      reply.from_uid as reply_from_uid, reply_from_user.name  as  reply_from_user_name, reply_from_user.realname as reply_from_user_realname, 
      reply.to_uid   as reply_to_uid,   reply_to_user.name    as  reply_to_user_name,   reply_to_user.realname as   reply_to_user_realname,
      reply.create_at as reply_create_at 
      FROM comment
      LEFT JOIN reply on reply.comment_id = comment.id
      LEFT JOIN user comment_user on comment.from_uid = comment_user.id
      LEFT JOIN user reply_from_user on reply.from_uid = reply_from_user.id
      LEFT JOIN user reply_to_user ON reply.to_uid = reply_to_user.id
       
      Where comment.article_id = ?
      AND comment.floor_num > ?
      AND comment.floor_num <= ?
      ORDER BY comment.floor_num ASC, reply.create_at ASC`
      const comments = await this.app.mysql.query(sql, [ article_id, (page - 1) * limit, page * limit ])
      let curr_floor_num = -1
      for (let i = 0; i < comments.length; i++) {
        // set replies always
        comments[i].replies = []
        if (!comments[i].reply_id) continue
        if (comments[i].floor_num !== curr_floor_num) {

          // fix loop bug
          comments[i].replies.push(JSON.parse(JSON.stringify(comments[i])))

          curr_floor_num = comments[i].floor_num
        } else {
          comments[i - 1].replies.push(comments.splice(i, 1)[0])
          i--
        }
      }
      return comments;
    }

    async create(params) {
      const article = await this.app.mysql.get('article', { id: params.article_id })
      const comment = await this.app.mysql.insert('comment', {
        content: params.content,
        floor_num: ++article.floor_num,
        article_id: params.article_id,
        article_type: article.type,
        from_uid: params.from_uid,
      })
      if (comment.affectedRows === 1) {
        await this.app.mysql.query('UPDATE article SET floor_num = floor_num + 1 WHERE id = ?', [ params.article_id ])
      }
      return { floor_num: article.floor_num, id: comment.insertId }
    }
  }

  return TopicService;
};
